package com.senlingspace.common.core.dingtalk;

import java.nio.charset.StandardCharsets;

/**
 * 钉钉消息工具类
 *
 * @author lebronjames
 * @date 2024/08/19
 */
public class DingTalkMessageUtil {

    public static final int MAX_MESSAGE_LENGTH = 2048;

    // 计算UTF-8编码下字符串的字节长度
    // 计算UTF-8编码下字符串的字符数
    public static int calculateUTF8Characters(String message) {
        int length = 0;
        byte[] utf8Bytes = message.getBytes(StandardCharsets.UTF_8);
        length = utf8Bytes.length;
        return length;
    }

    // 截取消息内容，确保其UTF-8编码后的字节长度不超过指定长度
    public static String truncateMessageIfNeeded(String message) {
        byte[] utf8Bytes = message.getBytes(StandardCharsets.UTF_8);
        if (utf8Bytes.length <= MAX_MESSAGE_LENGTH) {
            return message;
        } else {
            int endIndex = MAX_MESSAGE_LENGTH;
            while (endIndex > 0 && (utf8Bytes[endIndex] & 0xC0) == 0x80) {
                endIndex--;  // 确保不拆分多字节字符
            }
            return new String(utf8Bytes, 0, endIndex, StandardCharsets.UTF_8);
        }
    }

}
